<script setup>
import { reactive, ref } from "vue"
import { generateCaptcha, verifyCaptcha } from "@/api/login/login.js"
import { ElMessage } from "element-plus"
import { useStore } from "@/stores/store.js"
import {useRouter} from "vue-router";
import {debounce, throttle} from "lodash";

const router = useRouter()
const formData = ref({
  email: '',
  captcha: ''
})

const ruleFormRef = ref()
const countdown = ref(0)  // 用于存储倒计时
const isSending = ref(false)  // 用于控制验证码按钮的状态

const sendCaptcha = throttle((formEl) => {
  if (!formEl || isSending.value) return  // 如果正在倒计时，不允许重复点击

  // 只校验 email 字段
  formEl.validateField('email', (valid) => {
    if (valid) {
      // 请求发送验证码的接口
      generateCaptcha(formData.value.email).then(() => {
        ElMessage.success("验证码发送成功，请检查您的邮箱")
        // 开始倒计时
        startCountdown()
      })
    } else {
      console.log('邮箱验证未通过')
    }
  })
}, 5000)

const startCountdown = () => {
  countdown.value = 60 // 设置倒计时初始值为60秒
  isSending.value = true // 禁用发送验证码按钮

  const timer = setInterval(() => {
    countdown.value -= 1 // 每秒减少1

    if (countdown.value <= 0) {
      clearInterval(timer) // 停止计时器
      isSending.value = false // 启用按钮
    }
  }, 1000)
}

const submit = async (formEl) => {
  if (!formEl) return

  await formEl.validate((valid, fields) => {
    if (valid) {
      // 发起登录(验证)请求
      const email = formData.value.email
      const captcha = formData.value.captcha
      verifyCaptcha(email, captcha).then((res) => {
        useStore().admin.token = res.data
        useStore().admin.email = email.toString().trim()
        router.push('/')
      })
    } else {
      console.log('错误提交!', fields)
    }
  })
}

const rules = reactive({
  email: [
    { required: true, message: '请输入管理员邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入有效的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  captcha: [
    { required: true, message: '验证码不能为空', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码必须是6个字符', trigger: 'blur' }
  ]
})
</script>

<template>
  <div class="container">
    <div class="Box">
      <div class="left">
        <img src="../../assets/logo.png" alt="logo">
        <h4>FY音乐管理系统</h4>
        <p>欢迎来到管理系统</p>
      </div>
      <div class="right">
        <el-form class="form"
                 :model="formData"
                 ref="ruleFormRef"
                 :rules="rules"
        >
          <h3>欢迎登录</h3>
          <el-form-item style="margin-bottom: 20px;" prop="email">
            <input v-model="formData.email" type="text" placeholder="请输入邮箱" required>
          </el-form-item>
          <el-form-item style="margin-bottom: 15px; position: relative" prop="captcha">
            <input v-model="formData.captcha" placeholder="请输入验证码" required>
            <div
                @click="sendCaptcha(ruleFormRef)"
                class="send-btn"
                :class="{'disabled': isSending}"
                :style="{ color: isSending ? '#ccc' : 'rgb(19, 90, 150)'}"
            >
              {{ isSending ? `${countdown}秒` : '发送验证码' }}
            </div>
          </el-form-item>
          <div @click="submit(ruleFormRef)" class="loginBtn">登录</div>
          <p class="no">该系统账号不开放注册接口</p>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.send-btn {
  position: absolute;
  cursor: pointer;
  right: 10px;
  top: 0;
  line-height: 38px;
  font-size: 13px;
}

.send-btn.disabled {
  cursor: not-allowed;
}

.container {
  height: 100vh;
  background: url("@/assets/login/back.jpg") no-repeat;
  background-size: cover;
}

.Box {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 620px;
  height: 360px;
  display: flex;
}

.left {
  width: 50%;
  padding-top: 14%;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: linear-gradient(to left top, rgba(70, 2, 42, 0.35), rgba(31, 0, 31, 0.5)) ;
}

.right {
  position: relative;
  width: 55%;
  height: 100%;
  background-color:  rgba(255, 255, 255, 1);
}

.left img {
  width: 80px;
  height: 80px;
  margin-bottom: 5px;
}

.left p {
  font-size: 14px;
  color: #fff;
}

.left h4 {
  font-size: 19px;
  color: #fff;
  margin-bottom: 10px;
  font-style: italic;
}

.right .form {
  position: absolute;
  top: 55%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  text-align: center;
}

h3 {
  margin-bottom: 20px;
}

input {
  width: 100%;
  height: 38px;
  border-radius: 5px;
  border: 1px solid #767676;
  background-color: transparent;
  padding-left: 10px;
  font-size: 13px;
  color: #000000;
  outline: none;
}

.loginBtn {
  width: 100%;
  height: 38px;
  line-height: 38px;
  text-align: center;
  font-size: 15px;
  color: #fff;
  border-radius: 6px;
  background: rgb(57, 99, 134);
  outline: none;
  border: none;
  margin-top: 10px;
  cursor: pointer;
}

.no {
  cursor: pointer;
  margin-top: 30px;
  text-align: center;
  font-size: 12px;
  color: #828282;
}
</style>
